import React from 'react';
import ReactDOM from 'react-dom';
import * as config from '../../components/config/config';
import * as utils from '../../components/utils/utils';
import ajax from '../../components/ajax/ajax';
import { Toast, Modal } from 'antd-mobile';
import Loading from '../../components/loading/loading';
import Page from '../../components/page/page';
import SigninCalendar from './components/signinCalendar/signinCalendar';
import ContinueSignin from './components/continueSignin/continueSignin';
// import Lottery from './components/lottery/lottery';
import Banner from './components/banner/banner';
import SigninSuccessModal from './components/signinSuccessModal/signinSuccessModal';
import Navigator from '../../components/navigator/navigator';
import ScrollNumber from '../../components/scrollNumber/scrollNumber';
import AddCoinAnimation from './components/addCoinAnimation/addCoinAnimation';
import './index.css';

class SigninIndex extends React.Component {
    constructor (props) {
        super(props);

        this.state = {
            signinSucessModalVisible: false,
            continueSigninList: [],
            lotteryCount: 0,
            lotteryGiftList: [],
            banner: [],
            myCoinCount: 0,
            signinResult: {
                addedScore: 0,
                addedCoin: 0,
                getAwardNeedDays: false,
                awardType: 0
            },
            today: '',
            userToken: '',
            addCoinAnimation: {
                start: {},
                end: {}
            }
        };

        this.storage = {
            userToken: ''
        };
    }

    componentDidMount () {
        utils.getUserInfoFromQiuBaiApp().then((res) => {
            this.storage.userToken = res.Qbtoken;
            this.setState({
                userToken: res.Qbtoken
            });
            this.signin();
        }).catch((err) => {
            Toast.info(err.message || '获取用户信息失败');
        });
    }

    signin () {
        const signinLoading = Loading.show('加载中...');

        ajax.post({
            url: `${config.HOST_MISSION}${config.XHR_REQ_URL.SIGNIN}`,
            header: { Qbtoken: this.storage.userToken }
        }).then((res) => {
            signinLoading.hide();

            if (res.err === config.XHR_RES_CODE.SUCCESS) {
                const isSign = typeof (res.sign || {}).is_sign === 'undefined' ? true : (res.sign || {}).is_sign;
                // 领取奖励后的糗币总数
                const myCoinCount = (res.qiushi_mission || {}).coin_num || 0;
                // 领取的糗币
                const addedCoin = (res.sign || {}).add_coin || 0;

                this.setState({
                    signinResult: {
                        addedScore: (res.sign || {}).score,
                        addedCoin: addedCoin,
                        getAwardNeedDays: ((res.sign || {}).reward || {}).day,
                        awardType: ((res.sign || {}).reward || {}).activity
                    },
                    signinSucessModalVisible: !isSign,
                    myCoinCount: !isSign ? (myCoinCount - addedCoin) : myCoinCount, // 今天第一次签到，首先显示不算签到领取的糗币总数，弹框消失后再显示算签到领取的糗币总数
                    banner: res.banner,
                    lotteryCount: (res.award || {}).award_num,
                    lotteryGiftList: (res.award || {}).detail || [],
                    continueSigninList: res.sign_mission || [],
                    today: (res.sign || {}).today
                });
            }
            else {
                throw new Error(res.err_msg);
            }
        }).catch((err) => {
            signinLoading.hide();
            Toast.info(err.message || '签到失败');
        });
    }

    handleRulesBtnClick () {
        utils.disableDocumentScroll.add();

        Modal.alert(
            '签到规则',
            (
                <div style={{ textAlign: 'left' }}>
                    “7天连续签到活动”规则说明:<br />
                    1.签到7天为一个周期，第8天重新开始新一轮周期；<br />
                    2.连签7天任务内连续签到到特定天数（天数卡片上有奖励图标），将获得抽奖机会；<br />
                    3.活动为断签则重新开始计算，补签无效；
                </div>
            ),
            [{
                text: '确定',
                onPress: () => {
                    utils.disableDocumentScroll.remove();
                }
            }]
        );
    }

    getAddCoinAnimationPosotion () {
        const signedEleList = document.querySelectorAll('.signinList > .signed');
        const startEle = signedEleList[signedEleList.length - 1];
        const endEle = document.querySelector('.myCoin .unit');

        if (!startEle || !endEle) {
            return {
                start: {},
                end: {}
            };
        }

        const ballEle = document.querySelector('.addCoinAnimation > .ball');
        const endEleBound = endEle.getBoundingClientRect();
        const startEleBound = startEle.getBoundingClientRect();

        const offsetX = endEleBound.left + endEleBound.width / 2 - (startEleBound.left + startEleBound.width / 2);
        const offsetY = endEleBound.top + endEleBound.height / 2 - (startEleBound.top + startEleBound.height / 2);
        const scrollTop = document.documentElement.scrollTop || document.body.scrollTop || 0;
        const scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft || 0;

        return {
            start: {
                left: startEleBound.left + scrollLeft + ballEle.clientWidth / 2,
                top: startEleBound.top + scrollTop + ballEle.clientHeight
            },
            end: {
                left: offsetX,
                top: offsetY
            }
        };
    }

    handleSigninSuccessModalClose () {
        const animationPositon = window.requestAnimationFrame ? (this.getAddCoinAnimationPosotion() || {}) : {};

        this.setState((preState) => {
            return {
                myCoinCount: preState.myCoinCount + preState.signinResult.addedCoin,
                signinSucessModalVisible: false,
                addCoinAnimation: {
                    start: animationPositon.start,
                    end: animationPositon.end
                }
            };
        });
    }

    render () {
        return ([
            <Navigator
                key="navigator"
                title="签到"
                left={<div className="navigatorLeft" onClick={() => { utils.navigate.back(); }}></div>}
                right={<div className="ranking" onClick={() => { utils.navigate('mqsbk://check_in_top'); }}></div>}
            ></Navigator>,
            <Page key="page" pageName="comment">
                <div className="page-hd">
                    <div className="myCoin">
                        <p className="title">我的糗币</p>
                        <div className="num"><ScrollNumber value={this.state.myCoinCount}></ScrollNumber><span className="unit">个</span></div>
                    </div>
                    {/* <div className="btn-award"></div> */}
                    <div className="btn-rules" onClick={() => { this.handleRulesBtnClick(); }}></div>
                </div>
                <div className="page-bd">
                    <div className="signinAward">
                        <ContinueSignin list={this.state.continueSigninList} />
                        {/* <Lottery count={this.state.lotteryCount} list={this.state.lotteryGiftList} /> */}
                        <Banner list={this.state.banner} />
                    </div>
                    <SigninCalendar today={this.state.today} userToken={this.state.userToken} />
                </div>
                <SigninSuccessModal
                    result={this.state.signinResult}
                    visible={this.state.signinSucessModalVisible}
                    onClose={() => { this.handleSigninSuccessModalClose(); }}
                />
                {
                    window.requestAnimationFrame
                        ? <AddCoinAnimation
                            startPosition={this.state.addCoinAnimation.start}
                            endPosition={this.state.addCoinAnimation.end}
                            addNum={this.state.signinResult.addedCoin}
                            originalNum={this.state.myCoinCount}
                        ></AddCoinAnimation>
                        : null
                }
            </Page>
        ]);
    }
}

ReactDOM.render(
    <SigninIndex />,
    document.getElementById('pageWrapper')
);
